'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 用户
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var userSchema = require('../schemas/userSchema');
var User = mongoConnector().model('User');

/**
 * 根据uid获取用户
 */
module.exports.getByUid = function (uid, cb) {
    // 创建成功后
    function afterCreate(err, schema) {
        cb(err, schema);
    }

    // 查询成功后
    function afterFindOne(err, schema) {
        if (!!err) {
            return cb(err);
        }
        if (!!schema) {
            return _dealForbid(schema, cb);
        } else {
            User.create({
                uid: uid
            }, afterCreate);
        }
    }

    User.findOne({
        uid: uid
    }, afterFindOne);
};

/**
 * 获取封禁用户
 */
module.exports.getForbidUser = function (cb) {
    User.find({})
        .where('forbid')
        .equals('true')
        .select('uid reason end_time start_time forbid')
        .exec(cb);
};

/**
 * 处理封停状态
 */
var _dealForbid = function (user_model, cb) {
    if (user_model.isForbid()) {
        if (moment() >= user_model.getEndTime()) {
            user_model.unForbid();
            user_model.save(function (err) {
                if (!!err) {
                    console.error(err);
                    return cb(err);
                }
                cb(null, user_model);
            });
        } else {
            cb(null, user_model);
        }
    } else {
        cb(null, user_model);
    }
};
